import RowMaterialAPI from '../../../common/api/fs/writermaterial.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { Select2Page } from "../../../common/serve-request.js";


(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening"><div class="toolbar-inner"><span style='margin:0 auto;margin-top:10px'>请选择业务日期</span><a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a></div></div>`;
    let _vm, _pickerTime, index = 0, _ownOrgs = [], _stuffInfo = [], editintentionCity = [], editintentionArr = []
    const businessTemplate = doT.template($('#business-template').text());

    $(function () {
        _vm = new Vue({
            el: "#writermaterial",
            methods: {
                submit() {
                    savedata()
                }
            },
        });
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式

        _resetForm()
        _datetimePickerInit()
        saleOrgs()
        _initMaterial()
        _initContracts()

        _initCommand()
        _initcityPicker()
    });

    // 初始化命令
    const _initCommand = () => {
        // 类型
        requestDict(DictionaryType.Material_BUSINESS_TYPE).then(res => {
            $("#businessType").empty().append(businessTemplate(res.data));
        })
        $('#materialCode').on('select2:select', function () {
            let selectMaterial = $('#materialCode').select2('data')[0]
            $('#materialName').val(selectMaterial?.name || "")
            $('#materialCodes').val(selectMaterial?.numCode || "")
            $('#select2-materialCode-container').text(selectMaterial?.id || "")
        })
        if (Utils.IsNotNull($("#intentionCity").val())) {
            $('#clearCon').css('display', 'block')
        }
        else {
            $('#clearCon').css('display', 'none')
            editintentionCity = [], editintentionArr = [], index = 0
        }
        $('#clearCon').on('click', function () {
            $("#intentionCity").val('')
            if (Utils.IsNotNull($("#intentionCity").val())) {
                $('#clearCon').css('display', 'block')
            }
            else {
                $('#clearCon').css('display', 'none')
                editintentionCity = [], editintentionArr = [], index = 0
            }
        })

        $('#saleOrgs').on('select2:select', function () {
            let saleOrgsInfo = cutstr($('#select2-saleOrgs-container').text(), 20)
            $('#select2-saleOrgs-container').text(saleOrgsInfo)
        })
        $('#contractNum').on('select2:select', function () {
            let selcontractNum = cutstr($('#select2-contractNum-container').text(), 20)
            $('#select2-contractNum-container').text(selcontractNum)
        })


    }
    const _initContracts = async () => {
        Select2Page($(`#contractNum`), `${Utils.CurDomain.FeedstockUrl}/purcontracts`, (params) => {
            return ({
                BillStatus: 3,
                SearchInfo: params.term,
                PageSize: 10,
                PageIndex: (params.page || 1) - 1
            })
        }, "GET", {
            placeholder: '请选择合同单据编号...', //默认文字提示
            templateResult: function (res) {
                console.log(res)
                return `${res.billNo}(${res.numCode})`;
            },
            templateSelection: function (res) {
                return Utils.IsNotNull(res.billNo) ? `${res.billNo}` : "请选择合同单据编号...";
            }
        });
        $("#contractNum").setSelectValue();

    }

    // 初始化销售组织
    const saleOrgs = async () => {
        // _stuffInfo = await RowMaterialAPI.getUserInfo();
        _stuffInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {}
        _ownOrgs = await RowMaterialAPI.postUserOrgsList();
        let ownAccount = _ownOrgs.find(s => s.oId == _stuffInfo.coui);
        $('#saleOrgs').select2({
            placeholder: '请选择组织...', //默认文字提示
            language: "zh-CN",//汉化
            data: _ownOrgs.map(item => {
                return {
                    id: item.oId,
                    name: item.oName,
                    text: `${item.oName}(${item.oNumCode})`
                }
            }),
        });
        $("#saleOrgs").val(ownAccount?.oId).trigger('change')
        let saleOrgsInfo = cutstr($('#select2-saleOrgs-container').text(), 20)
        $('#select2-saleOrgs-container').text(saleOrgsInfo)
    }
    // 初始化物料
    const _initMaterial = async () => {
        Select2Page($(`#materialCode`), `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`, (params) => {
            return ({
                Status: true,
                SearchInfo: params.term,
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            })
        }, "GET", {
            placeholder: '请选择物料...', //默认文字提示
            templateResult: function (res) {
                console.log(res)
                return `${res.name}(${res.numCode})`;
            },
            templateSelection: function (res) {
                return Utils.IsNotNull(res.id) ? `${res.numCode}` : "请选择物料...";
            }

        });
        $("#materialid").setSelectValue();
    }
    //业务日期控件初始化
    const _datetimePickerInit = () => {
        let todayDate = moment().format('YYYY-MM-DD')
        $('#businessTime').val(todayDate)
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#search-date').on('click', function (e) {
            e.stopPropagation();
            $("#search-date").picker("open");
            _pickerDate();
        });
        $("#search-date").datetimePicker(
            {
                toolbarTemplate: toolbarTemplate,
                toolbarCloseText: "确定",
                toolbarCancelText: "取消",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },
                //确定选择时的操作
                onClose: function (picker) {
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
                    _pickerTime = '';
                    _pickerTime = value;
                }
            }
        );
    }
    //业务日期确认事件
    const _pickerDate = () => {
        $(document).on("click", ".close-picker", function () {
            $('#businessTime').val(_pickerTime);
        });
    }
    // 初始化意向城市
    const _initcityPicker = () => {
        // 取消按钮
        $('#canvalBtn').on('click', function () {
            $('#maskback').css('display', 'none')
            // $('body').removeClass('disablemask')
            document.body.style.overflow = 'scroll'
            document.body.style.position = 'relative'
            $("html,body").stop().animate({
                scrollTop: $("body").height()
            }, 300);

        })
        // 确定按钮
        $('#determineBtn').on('click', function () {
            let selectArr = []
            $('#selectCity').find('.innerAddress').each((index, item) => {
                let selectAddresss = $(item).text()
                if (Utils.IsNotNull(selectAddresss) && selectAddresss != '请选择') {
                    selectArr.push(selectAddresss)
                }
            })
            let selectCity = selectArr.join('-')
            $('#intentionCity').val(selectCity)
            $('#canvalBtn').click()
            editintentionCity = selectCity
            $('#clearCon').css('display', 'block')
        })
        // 点击灰色遮罩层
        $('#unimportmask').on('click', function () {
            $('#canvalBtn').click()
        })
        // 点击意向城市
        $(document).on('click', '#search-intentionCity ', function () {
            // 关闭键盘
            document.activeElement.blur();
            // body禁止滚动
            document.body.style.position = 'fixed'
            document.body.style.overflow = 'hidden'
            $('#intentionContain').children('div').eq(0).empty()
            $('#intentionContain').children('div').eq(0).siblings().empty()

            index = 0
            getAddress('province', "").then(res => {
                if (Utils.IsNotNull(editintentionCity)) {
                    editintentionArr = editintentionCity.split('-')
                    let editaddress = res.filter(item => {
                        return item.name == editintentionArr[0]
                    })
                    if (Utils.IsNotNull(editaddress)) {
                        $(`#${editaddress[0].id}`).click()
                    }
                }
                else {
                    $('#selectCity').empty().append(` <li class="activeStyle towellipse"><span id="provice" class="innerAddress">请选择</span>
                    <div class="uderline underlineit"></div></li><li class="towellipse"><span id="city" class="innerAddress"></span>
                    <div class="uderline"></div></li><li class="towellipse"><span id="district" class="innerAddress"></span><div class="uderline"></div></li>`)
                }
            })
            setTimeout(() => {
                $('#maskback').css('display', 'block')
            }, 200);
        })
        $('#returnMain').on('click', function () {
            location.href = `../../main.html?v=${Utils.GetTime()} `;
        })
        // 点击导航栏
        $('#selectCity').on('click', 'li', function () {
            editintentionArr = []
            $(this).addClass('activeStyle').siblings('li').removeClass('activeStyle')
            $(this).find('.uderline').addClass('underlineit')
            $(this).siblings('li').find('.uderline').removeClass('underlineit')
            index = $(this).index()
            $('#intentionContain').children('div').eq(index).css('display', 'block').siblings('div').css('display', 'none')
        })
        // 选择之后
        $(document).on('click', '.addressCon', async function () {
            let addressid = $(this).attr('id')
            let addressName = $(this).text()
            $('#selectCity').find('li').eq(index).find('span').text(addressName)
            $(this).addClass('activeStyle').siblings('div').removeClass('activeStyle')
            index = index + 1
            changeStyle(index)
            $('#intentionContain').children('div').eq(index).empty()
            if (index == 1) {
                getAddress('city', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[1])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[1]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
                let nextNav = $('#selectCity').find('li').eq(index + 1).find('span')
                if (Utils.IsNotNull(nextNav.text())) {
                    nextNav.text('')
                }
            }
            else if (index == 2) {
                getAddress('district', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[2])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[2]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
            }
            else if (index > 2) {
                $('#selectCity').find('li').eq(2).find('span').text(addressName)
            }
        })
    }
    const changeStyle = (id) => {
        $('#selectCity').find('li').eq(id).find('span').text('请选择')
        $('#selectCity').find('li').eq(id).addClass('activeStyle').siblings('li').removeClass('activeStyle')
        $('#selectCity').find('li').eq(id).find('.uderline').addClass('underlineit')
        $('#selectCity').find('li').eq(id).siblings('li').find('.uderline').removeClass('underlineit')
    }
    // 获取地点 联动
    const getAddress = async (level, pid) => {
        return new Promise((resolve, reject) => {
            getDistory(level, pid).then(res => {
                let addressData
                if (index == 0) {
                    addressData = [...res]
                }
                else {
                    addressData = [...res]
                }
                $('#intentionContain').children('div').eq(index).css('display', 'block').siblings('div').css('display', 'none')
                addressData.forEach(item => {
                    $('#intentionContain').children('div').eq(index).append(`<div class="addressCon" id="${item.id}" style="margin-bottom:8px">${item.name}</div>`)
                })
                resolve(addressData)
            })
        })
    }
    const getDistory = (type, id) => {
        return new Promise((resolve, reject) => {
            RowMaterialAPI.getDistrictsType(type, id).then(res => {
                resolve(res)
            })
        })
    }
    const _resetForm = () => {
        $('.weui-input').val('')
    }
    // 保存
    const savedata = () => {
        if (!Utils.IsNotNull($('input[name="optradio"]:checked').val())) return $.toptip(`请选择类型!`, 'warning');
        if (!Utils.IsNotNull($('#businessTime').val())) return $.toptip(`请选择业务日期!`, 'warning');
        if (!Utils.IsNotNull($('#saleOrgs').select2('data')[0])) return $.toptip(`请选择组织!`, 'warning');
        if (!Utils.IsNotNull($('#materialCodes').val())) return $.toptip(`请选择物料!`, 'warning');
        if (!Utils.IsNotNull($('#quantity').val())) return $.toptip(`请输入数量!`, 'warning');
        // if (!Utils.IsNotNull($('#contractNum').val())) return $.toptip(`请输入合同单据编号!`, 'warning');
        var reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
        if (!$('#quantity').val().match(reg)) return $.toptip(`数量必须大于0并且只能保留两位小数`, 'warning')
        savetips()
    }
    // 保存提示
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >是否确认保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        let _param = {
                            "material": {
                                "name": $('#materialName').val(),
                                "numCode": $('#materialCodes').val()
                            },
                            "purOrg": {
                                "id": $('#saleOrgs').select2('data')[0]?.id || "",
                                "name": $('#saleOrgs').select2('data')[0]?.name || ""
                            },
                            "bizDate": $('#businessTime').val(),
                            "type": $('input[name="optradio"]:checked').val(),
                            "qty": $('#quantity').val(),
                            "contractNo": $('#contractNum').val(),
                            "sourcePlace": $('#intentionCity').val(),
                            "carNo": $('#contractNum').select2('data')[0]?.billNo || ""
                        }
                        RowMaterialAPI.addRowMaterial(_param).then(res => {
                            $.toptip('请求成功。', 'success');
                            location.href = `../../main.html?v=${Utils.GetTime()} `;
                        })
                    }
                }
            ]
        });
    }

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
})(window, document, jQuery)